package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.PageReservationDto;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.MemberProjectMapper;
import com.zzyl.nursing.mapper.MemberReservationMapper;
import com.zzyl.nursing.service.IMemberReservationService;
import com.zzyl.nursing.vo.TimeSlotCountVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MemberReservationServiceImpl extends ServiceImpl<MemberReservationMapper, Reservation> implements IMemberReservationService {
    @Autowired
    private MemberReservationMapper memberReservationMapper;
    @Override
    public void insert(ReservationDto reservationDto) {
        Reservation reservation = BeanUtil.copyProperties(reservationDto, Reservation.class);
        //补充信息
        reservation.setStatus(0);
        save(reservation);
        return;
    }

    @Override
    public TableDataInfo<Reservation> pageReservation(PageReservationDto pageReservationDto) {
        PageHelper.startPage(pageReservationDto.getPageNum(),pageReservationDto.getPageSize());
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();


        queryWrapper.like(pageReservationDto.getStatus()!=null,Reservation::getStatus,pageReservationDto.getStatus());
        List<Reservation> list = list(queryWrapper);
        Page<Reservation> page = (Page<Reservation>) list;
        TableDataInfo<Reservation> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("操作成功");
        return tableDataInfo;

    }

    @Override
    public Integer countToday() {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        return memberReservationMapper.countTodayCancelled(
                startTime,
                endTime,
                2
        );


    }

    @Override
    public void cancel(Integer id) {
        LambdaUpdateWrapper<Reservation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Reservation::getId,id).set(Reservation::getStatus,2);
        update(updateWrapper);

    }

    @Override
    public List<TimeSlotCountVo> countByTime() {
        // 1. 查询当天已预约的各时间段次数
        List<TimeSlotCountVo> reservedList = memberReservationMapper.countReservedByTime();

        // 2. 动态生成“当天的所有可选时间段”
        // 2.1 获取当前日期（如 2024-10-10）
        LocalDate today = LocalDate.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String todayStr = today.format(dateFormatter); // 转为字符串："2024-10-10"

        // 2.2 定义固定的时间点（上午+下午），拼接当前日期
        String[] timePoints = {
                "08:00:00", "08:30:00", "09:00:00", "09:30:00",
                "10:00:00", "10:30:00", "11:00:00", "11:30:00", "12:00:00",
                "12:30:00", "13:00:00", "13:30:00", "14:00:00",
                "14:30:00", "15:00:00", "15:30:00", "16:00:00",
                "16:30:00", "17:00:00", "17:30:00", "18:00:00"
        };

        // 2.3 拼接成“当天的完整时间段”（如 "2024-10-10 08:00:00"）
        String[] allTimeSlots = Arrays.stream(timePoints)
                .map(timePoint -> todayStr + " " + timePoint)
                .toArray(String[]::new);

        int maxCount = 6;

        // 3. 计算每个时间段的“剩余次数”（maxCount - 已预约数）
        return calculateRemainingCount(allTimeSlots, reservedList, maxCount);
    }


    private List<TimeSlotCountVo> calculateRemainingCount(
            String[] allTimeSlots,
            List<TimeSlotCountVo> reservedList,
            int maxCount) {
        // 遍历所有当天时间段，计算剩余次数
        return Arrays.stream(allTimeSlots)
                .map(timeSlot -> {
                    // 1. 创建一个 Vo 对象，存储当前时间段的结果
                    TimeSlotCountVo vo = new TimeSlotCountVo();
                    vo.setTime(timeSlot); // 设置时间段（如 "2024-10-10 08:00:00"）

                    // 2. 从数据库查询的“已预约列表”中，找到当前时间段的已预约次数
                    // 如果该时间段没人预约，默认已预约次数为 0
                    int reservedCount = reservedList.stream()
                            // 匹配时间段（字符串完全相等，确保是同一个时间点）
                            .filter(reservedVo -> timeSlot.equals(reservedVo.getTime()))
                            .findFirst() // 找到第一个匹配的记录
                            .map(TimeSlotCountVo::getCount) // 提取已预约次数
                            .orElse(0); // 没找到时，默认已预约 0 次

                    // 3. 剩余次数 = 最大可预约次数 - 已预约次数
                    vo.setCount(maxCount - reservedCount);

                    return vo;
                })
                .collect(Collectors.toList()); // 把所有结果收集成列表返回
    }
}
